package idv.loveloser.mobilemoodle;

import com.google.gson.Gson;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class MobilemoodleActivity extends Activity {
    /** Called when the activity is first created. */
	private EditText usernameEditText,passwordEditText;
	private Button loginBtn;
	private SharedPreferences sets;
	private SharedPreferences.Editor editor;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        usernameEditText = (EditText) findViewById(R.id.usernameEditText);
        passwordEditText = (EditText) findViewById(R.id.passwordEditText);
        loginBtn = (Button) findViewById(R.id.loginLoginBtn);
        sets=getApplicationContext().getSharedPreferences("MySettings", MODE_WORLD_WRITEABLE );
        editor=sets.edit();
        loginBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String username=usernameEditText.getText().toString();
				String password=passwordEditText.getText().toString();
				String loginReturnStr=Util.login(username, password);
				if(loginReturnStr.length()==0)
					Toast.makeText(getApplicationContext(), "Login Fail", Toast.LENGTH_LONG).show();
				else{
					Gson gson = new Gson();
					LoginReturn lr=gson.fromJson(loginReturnStr, LoginReturn.class);
					editor.putString("sessionKey", lr.getSessionKey());
					editor.putLong("client", lr.getClient());
					editor.putBoolean("hasRight", lr.isHasRight());
					editor.commit();
					Intent mainIntent = new Intent(getApplicationContext(),MainActivity.class);
					startActivity(mainIntent);
				}					
			}
		});
    }
}